package com.ft.oa.utils;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 文件上传
 */
public class FileUtil {

    public static HashMap<String,List<String>> getFileUpload(MultipartFile[] files,String uploadFilePath) {
        HashMap<String,List<String>> hashMap = new HashMap<>();
        List<String> newlist = new ArrayList();
        ArrayList<String> oldlist = new ArrayList<>();
        for (int i = 0; i < files.length; i++) {
            String fileName = files[i].getOriginalFilename(); //原文件名称
            Date date = new Date();
            int num = (int)(Math.random()*1000000);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            String newfileName = sdf.format(date) +num +suffixName; //新文件名
            File dest = new File(uploadFilePath + '/' + newfileName);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            try {
                files[i].transferTo(dest);
            } catch (Exception e) {

                //list.add("上传失败");
                return hashMap;
            }
            oldlist.add(fileName);
            newlist.add(newfileName);
            hashMap.put("oldlist",oldlist);
            hashMap.put("newlist",newlist);
            }
            //list.add(addr+":9999/file/"+fileName);
            return hashMap;

    }

    /**
     * 文件下载
     */

    public static  String getFileDownload(HttpServletResponse response,String fileName) {
        String downloadFilePath = "D:/test";
        File file = new File(downloadFilePath + '/' + fileName);
        if (!file.exists()) {
            return "下载文件不存在";
        }
        response.reset();
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setContentLength((int) file.length());
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
            byte[] buff = new byte[1024];
            OutputStream os = response.getOutputStream();
            int i = 0;
            while ((i = bis.read(buff)) != -1) {
                os.write(buff, 0, i);
                os.flush();
            }
        } catch (IOException e) {
            return "下载失败";
        }
        return "下载成功";
    }
}
